import { NextFunction, Request, Response } from 'express'

interface RateLimitStore {
  [key: string]: {
    count: number
    resetTime: number
  }
}

const store: RateLimitStore = {}

const createRateLimiter = (windowMs: number, max: number, message: string) => {
  return (req: Request, res: Response, next: NextFunction) => {
    const key = req.ip
    const now = Date.now()

    if (!key) {
      return next()
    }

    // 清理过期的记录
    if (store[key]?.resetTime && store[key].resetTime <= now) {
      delete store[key]
    }

    // 初始化或更新记录
    if (!store[key]) {
      store[key] = {
        count: 0,
        resetTime: now + windowMs,
      }
    }
    const record = store[key]!
    record.count++

    // 检查是否超过限制
    if (record.count > max) {
      return res.status(429).json({
        status: 'error',
        message,
      })
    }

    next()
  }
}

// 通用限流
export const generalLimiter = createRateLimiter(
  15 * 60 * 1000, // 15分钟
  100, // 100次请求
  '请求过于频繁，请稍后再试'
)

// 登录限流
export const loginLimiter = createRateLimiter(
  15 * 60 * 1000, // 15分钟
  5, // 5次尝试
  '登录尝试次数过多，请15分钟后再试'
)

// API限流
export const apiLimiter = createRateLimiter(
  60 * 1000, // 1分钟
  30, // 30次请求
  'API请求过于频繁，请稍后再试'
)
